package com.itheima.redbaby.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.R;
import com.itheima.redbaby.bean.Area;
import com.itheima.redbaby.dao.domain.AddressDo;
import com.itheima.redbaby.engine.AddressEngine;
import com.itheima.redbaby.factory.DaoAndEngineFactory;
import com.itheima.redbaby.utils.DensityUtil;
import com.itheima.redbaby.utils.PromptManager;


public class AddAddressActivity extends BaseActivity implements OnClickListener {
	
	public static final int OK=1;
	public static final int ERROR=2;
	
	private EditText name;
	private EditText phoneNum;
	private EditText fixedTel;
	private TextView provinceName;
	private TextView cityName;
	private TextView areaName;
	private EditText areaDetial;
	private EditText zipcode;
	private Button btSave;
	private Button btCancel;
	private TextView tv_add_address_save;
	private TextView tv_add_address_back;
	
	
	private List<Area> areaes;
	private Area selected;
	private ListView list;
	private PopupWindow pw;
	private AreaListAdapter adapter;
	
	private Area selectedPro;
	private Area selectedCity;
	
	AddressEngine impl;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_address_activity);
		
		initView();
	}

	private void initView() {
		impl = DaoAndEngineFactory.getImpl(AddressEngine.class);
		list=new ListView(this);
		name=(EditText) findViewById(R.id.add_address_name_edit);
		phoneNum=(EditText) findViewById(R.id.add_address_mobile_edit);
		fixedTel=(EditText) findViewById(R.id.add_address_tel_edit);
		provinceName=(TextView) findViewById(R.id.add_address_province_name_text);
		cityName=(TextView) findViewById(R.id.add_address_city_name_text);
		areaName=(TextView) findViewById(R.id.add_address_area_name_text);
		areaDetial=(EditText) findViewById(R.id.add_address_detail_edit);
		zipcode=(EditText) findViewById(R.id.add_address_zipcode_edit);
		
		tv_add_address_save = (TextView) findViewById(R.id.tv_add_address_save);
		tv_add_address_back = (TextView) findViewById(R.id.tv_add_address_back);
		
		btSave = (Button) findViewById(R.id.save_address_button);
		btCancel = (Button) findViewById(R.id.cancel_address_button);
		
		btSave.setOnClickListener(this);
		btCancel.setOnClickListener(this);
		tv_add_address_back.setOnClickListener(this);
		tv_add_address_save.setOnClickListener(this);
		
		provinceName.setOnClickListener(this);
		cityName.setOnClickListener(this);
		areaName.setOnClickListener(this);
	
		}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_add_address_save:
		case R.id.save_address_button:
			saveData();
			break;
		case R.id.cancel_address_button:
			finish();
			break;
		case R.id.tv_add_address_back:
			finish();
			break;
		case R.id.add_address_province_name_text:
			selectProvince();
			break;
		case R.id.add_address_city_name_text:
			selectCity();
			break;
		case R.id.add_address_area_name_text:
			selectArea();
			break;

		default:
			break;
		}
		
	}

	private void selectArea() {
		new MyHttpTask() {
			
			@Override
			protected Object doInBackground(Void... params) {
				if(selected!=null&&selected.getValue()==areaName.getText().toString()){
					areaes=impl.getAreaByParentId(selectedCity.getId());
					return OK;
				}
				
				if(selected==null ||selected.getValue()!=cityName.getText().toString())
					return ERROR;
				areaes=impl.getAreaByParentId(selected.getId());
				selectedCity=selected;
				return OK;
				
			}
			protected void onPostExecute(Object result) {
				int state=(Integer)result;
				if(state==ERROR){
					return;
				}
				if (areaes != null && areaes.size() > 0) {
					showPop(areaName);
					dismissPop(areaName);
				}
				
			};
		}.executeHttp();
		
	}

	private void selectCity() {
		areaName.setText("请选择");
		
		new MyHttpTask() {
			
			@Override
			protected Object doInBackground(Void... params) {
				if(selected!=null&&selected.getValue()==cityName.getText().toString()){
					areaes=impl.getAreaByParentId(selectedPro.getId());
					return OK;
				}
				
				if(selected==null ||selected.getValue()!=provinceName.getText().toString())
					return ERROR;
				areaes=impl.getAreaByParentId(selected.getId());
				selectedPro=selected;
				return OK;
			}
			protected void onPostExecute(Object result) {
				int state=(Integer)result;
				if(state==ERROR){
					return;
				}
				if (areaes != null && areaes.size() > 0) {
					showPop(cityName);
					dismissPop(cityName);
				}
				
			};
		}.executeHttp();
		
	}

	private void selectProvince() {
		cityName.setText("请选择");
		areaName.setText("请选择");
		
		new MyHttpTask() {
			
			@Override
			protected Object doInBackground(Void... params) {
				areaes=impl.getAreaByParentId(0);
				return null;
			}
			protected void onPostExecute(Object result) {
				if (areaes != null && areaes.size() > 0) {
					showPop(provinceName);
					dismissPop(provinceName);
				}
				
			};
		}.executeHttp();
		
	}
	
	/**
	 * 显示下拉框
	 * 
	 * @param view
	 */
	private void showPop(TextView view) {
		list.setVerticalScrollBarEnabled(false);
		list.setDivider(null);
		list.setDividerHeight(0);
		adapter = new AreaListAdapter();
		list.setAdapter(adapter);
		pw = new PopupWindow(list, view.getWidth(), DensityUtil.dip2px(this,
				80));
		pw.setBackgroundDrawable(new ColorDrawable(Color.LTGRAY));
		pw.setFocusable(true);
		pw.setOutsideTouchable(true);

		pw.showAsDropDown(view, 0, -3);
	}
	
	/**
	 * 隐藏下拉框
	 * 
	 * @param tv
	 */
	private void dismissPop(final TextView tv) {
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				selected = areaes.get(position);
				tv.setText(selected.getValue());
				pw.dismiss();
			}
		});

	}

	private void saveData() {
		
		String name = this.name.getText().toString().trim();
		String phoneNum = this.phoneNum.getText().toString().trim();
		String fixedTel = this.fixedTel.getText().toString().trim();
		String provinceName = this.provinceName.getText().toString().trim();
		String cityName = this.cityName.getText().toString().trim();
		String areaName = this.areaName.getText().toString().trim();
		String areaDetial = this.areaDetial.getText().toString().trim();
		String zipcode = this.zipcode.getText().toString().trim();
		if (StringUtils.isBlank(name)) {
			PromptManager.showToast(this, "请填写收货人姓名");
			return;
		}
		if (StringUtils.isBlank(phoneNum)) {
			PromptManager.showToast(this, "请填写手机号码");
			return;
		}
		if (StringUtils.isBlank(fixedTel)) {
			PromptManager.showToast(this, "请填写固定电话");
			return;
		}
		if ("请选择".equals(provinceName)) {
			PromptManager.showToast(this, "请选择省份");
			return;
		}
		if ("请选择".equals(cityName)) {
			PromptManager.showToast(this, "请选择城市");
			return;
		}
		if ("请选择".equals(areaName)) {
			PromptManager.showToast(this, "请选择地区");
			return;
		}
		if (StringUtils.isBlank(areaDetial)) {
			PromptManager.showToast(this, "请填写详细地址");
			return;
		}
		if (StringUtils.isBlank(zipcode)) {
			PromptManager.showToast(this, "请填写邮政编码");
			return;
		}
		
		/*AddressDo address=new AddressDo();
		address.setAreaDetail(areaDetial);
		address.setAreaId(selected.getId());
		address.setCityId(selectedCity.getId());
		address.setFixedtel(fixedTel);
		address.setName(name);
		address.setPhonenumber(phoneNum);
		address.setProvinceId(selectedPro.getId());
		address.setZipCode(zipcode);*/
		
		final Map<String,Object> addmap=new HashMap<String, Object>();
		
		addmap.put("name", name);
		addmap.put("phonenumber", phoneNum);
		addmap.put("fixedtel", fixedTel);
		addmap.put("areaid", selected.getId());
		addmap.put("areadetail", areaDetial);
		addmap.put("zipcode", zipcode);
		
		new MyHttpTask() {
			
			@Override
			protected Object doInBackground(Void... params) {
				return impl.insertAddress(addmap);
				
			}
			protected void onPostExecute(Object result) {
				List<AddressDo> addressList=(List<AddressDo>) result;
				if(addressList.size()>0){
					PromptManager.showToast(AddAddressActivity.this, "插入成功");
					
					Intent data=new Intent();
					Bundle extras=new Bundle();
					
					data.putExtra("addressList", extras);
					
					setResult(Activity.RESULT_OK);
					finish();
				}else{
					PromptManager.showToast(AddAddressActivity.this, "插入失败");
					
				}
			};
		}.executeHttp();
		
	}
	
	
	
	
	
	class AreaListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return areaes.size();
		}

		@Override
		public Object getItem(int position) {
			return areaes.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			TextView view = new TextView(AddAddressActivity.this);
			view.setText(areaes.get(position).getValue());
			view.setTextColor(Color.BLACK);
			return view;
		}
	}
	
}
